'use strict';
const db = uniCloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { id, title, categoryId, status, description, tags } = event;
    const { OPENID } = context;
    
    // 验证请求参数
    if (!id) {
      return {
        code: 400,
        message: '壁纸ID不能为空'
      };
    }
    
    if (!title || title.trim() === '') {
      return {
        code: 400,
        message: '壁纸标题不能为空'
      };
    }
    
    // 验证标题长度
    if (title.length > 50) {
      return {
        code: 400,
        message: '壁纸标题长度不能超过50个字符'
      };
    }
    
    if (!categoryId) {
      return {
        code: 400,
        message: '壁纸分类不能为空'
      };
    }
    
    // 验证状态值
    const validStatuses = [0, 1, 'active', 'inactive', 'approved', 'disabled'];
    if (status !== undefined && !validStatuses.includes(status)) {
      return {
        code: 400,
        message: '壁纸状态值无效'
      };
    }
    
    // 验证标签
    if (tags && !Array.isArray(tags)) {
      return {
        code: 400,
        message: '标签必须是数组格式'
      };
    }
    
    // 验证标签数量和长度
    if (tags && tags.length > 10) {
      return {
        code: 400,
        message: '标签数量不能超过10个'
      };
    }
    
    if (tags) {
      for (const tag of tags) {
        if (typeof tag !== 'string' || tag.length > 20) {
          return {
            code: 400,
            message: '标签必须是字符串且长度不超过20个字符'
          };
        }
      }
    }
    
    // 验证管理员权限
    const adminInfo = await db.collection('admin_users')
      .where({
        openid: OPENID,
        is_active: true
      })
      .field({
        _id: 1,
        username: 1,
        role: 1
      })
      .get();
    
    // if (adminInfo.data.length === 0) {
    //   return {
    //     code: 403,
    //     message: '您没有管理员权限'
    //   };
    // }
    
    // 验证分类是否存在
    const categoryInfo = await db.collection('categories')
      .doc(categoryId)
      .get();
    
    if (!categoryInfo.data || !categoryInfo.data[0]) {
      return {
        code: 400,
        message: '指定的分类不存在'
      };
    }
    
    // 验证壁纸是否存在
    const wallpaperInfo = await db.collection('wallpapers')
      .doc(id)
      .get();
    
    if (!wallpaperInfo.data || !wallpaperInfo.data[0]) {
      return {
        code: 404,
        message: '壁纸不存在'
      };
    }
    
    const oldWallpaper = wallpaperInfo.data[0];
    
    // 构建更新数据
    const updateData = {
      title: title.trim(),
      categoryId,
      update_time: Date.now()
    };
    
    // 添加可选字段
    if (status !== undefined) {
      // 规范化状态值
      const normalizedStatus = status === 'active' || status === 'approved' ? 1 : 
                             status === 'inactive' || status === 'disabled' ? 0 : 
                             Number(status);
      updateData.status = normalizedStatus;
    }
    
    if (description !== undefined) {
      // 验证描述长度
      if (description.length > 200) {
        return {
          code: 400,
          message: '壁纸描述长度不能超过200个字符'
        };
      }
      updateData.description = description.trim();
    }
    
    if (tags !== undefined) {
      updateData.tags = tags;
    }
    
    // 执行事务更新
    const transaction = await db.startTransaction();
    
    try {
      // 更新壁纸信息
      await transaction.collection('wallpapers')
        .doc(id)
        .update(updateData);
      
      // 记录操作日志
      await transaction.collection('admin_logs').add({
        admin_id: adminInfo.data[0]._id,
        admin_name: adminInfo.data[0].username,
        action: 'update_wallpaper',
        target_id: id,
        target_title: title.trim(),
        changes: updateData,
        create_time: Date.now()
      });
      
      // 提交事务
      await transaction.commit();
      
      return {
        code: 0,
        message: '更新壁纸成功',
        data: {
          id,
          ...updateData
        }
      };
      
    } catch (err) {
      // 回滚事务
      await transaction.rollback();
      throw err;
    }
    
  } catch (error) {
    console.error('更新壁纸失败:', error);
    return {
      code: 500,
      message: '更新壁纸失败，请稍后重试',
      error: error.message
    };
  }
};